<?php

/*
销售出库
*/
namespace Modules\Salesmanagement\Http\Repositories;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Promanagement\Models\Processflow;
use Modules\Promanagement\Models\Provflowsional;
use extend\services\warehouse\{warehouseService};//引入自定义类
use Modules\Purchasing\Http\Repositories\PurchaseorderReget;
use Modules\Salesmanagement\Models\SalesoutAttached;
use Modules\Salesmanagement\Models\Salesout;
use Modules\Salesmanagement\Models\SalesoutTiaoma;
use App\Services\InventoryService;
use App\Services\KingDeeService;
use Modules\Salesmanagement\Models\Salesreturn;
use Modules\Salesmanagement\Models\SalesreturnAttached;
use App\Enums\InvTransDocType;
use Modules\Purchasing\Models\Purchasereturn;
use Modules\Purchasing\Models\PurchasereturnAttached;
use Modules\Purchasing\Models\PurchasewarehousingMateriel;
use Modules\Warehouse\Models\Storagelocation;


class SalesreturnRequest
{
   
 
    /*
    数据列表
    */
    public static function list($data = [])
    {
        // return self::getBuilder($data);
        return self::getBuilder($data)->paginate($data['per_page'] ?? 20);
    }

     /**
     *查询列表
     *
     * @param array $data
     * @return Builder
     */
    public static function getBuilder(array $data = []): Builder
    {
       
        // $builder = Provisional::query()->with('detailscheckAll');
        $builder = Salesout::query();
        if (isset($data['fbillno'])) {
            $builder->where('fbillno', 'like', "%{$data['fbillno']}%");
        }

        if (isset($data['fcustomerid_number'])) {
            $builder->where('fcustomerid_number', 'like', "%{$data['fcustomerid_number']}%");
        }

        if (isset($data['state'])) {
            $builder->where('state',$data['state']);
        }
        $builder->orderBy('id', 'desc');
        $builder->get()->toArray();
        return $builder;
    }

    /*
    列表详情接口
    */
    public static function SalesdetailsData($id)
    {

        $data = SalesoutAttached::where('salesout_id',$id)
        ->get()
        ->toArray();
        return ['code'=>1000,'message'=>'请求成功','data'=>$data];
    }

    /*
    数据添加方法
    */
    public static function create(array $data)
    {
   
        $Salesreturn = new Salesreturn;
        return self::createOrSave($Salesreturn, $data);
    }

    //数据添加方法
    public static function createOrSave(Salesreturn $Salesreturn,$data)
    {
     

        try {
            //开始起事务
            DB::beginTransaction();
            
            $Salesoutdata = [];
            $Salesoutdata['returnnumber'] = \App\Services\UnitService::createDocno(\App\Enums\OrderNoPrefix::NO_XSTH->value);
            $Salesoutdata['remark'] = $data['remark'] ?? "";
            $Salesoutdata['incomingtype'] = $data['incomingtype'] ?? 0;
            $Salesoutdata['creator_id'] = $data['creator_id'];
            $Salesreturn->fill($Salesoutdata);
            $Salesreturn->save();
            $Salesreturn->detailscheckAll()->createMany( $data['detailscheck_all'] );

            DB::commit();
            return ['code'=>1000,'message'=>'提交成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException($e);
        }
    }

    //修改
    public static function createUpdate($fid,$data)
    {
        try {
            //开始起事务
            DB::beginTransaction();
            $Salesout = Salesout::query()->updateOrCreate(['fid' => $fid], [
                'fbillno'       => $data['fbillno']  ?? '',
                'fsaleorgid_number'       => $data['fsaleorgid_number']  ?? '',
                'fsaleorgid_name'       => $data['fsaleorgid_name']  ?? '',
                'fcustomerid_number'       => $data['fcustomerid_number']  ?? '',
                'fcustomerid_name'       => $data['fcustomerid_name']  ?? '',
                'fdocumentstatus'       => $data['fdocumentstatus']  ?? '',
            ]);
            foreach($data['FEntry'] as $k=>$v){
                 $SalesoutAttached = SalesoutAttached::query()->select('id')->where('fid',$fid)->where('fseq',$v['fseq'])->where('fentryid',$v['fentryid'])->first();
                if(empty($SalesoutAttached)){
                    throw new FailedException('单据体出错');
                }
                SalesoutAttached::query()->where('id',$SalesoutAttached->id)->update(
                    [
                        'fmaterialid'=>$v['fmaterialid'],
                        'fmaterialname'=>$v['fmaterialname'],
                        'fmaterialmodel'=>$v['fmaterialmodel'],
                        'fmodel'=>$v['fmodel'],
                        'funitid_number'=>$v['funitid_number'],
                        'funitid_name'=>$v['funitid_name'],
                        'fqty'=>$v['fqty'],
                        'fstockid_number'=>$v['fstockid_number'],
                        'fstockid_name'=>$v['fstockid_name'],
                        'fmemo'=>$v['fmemo'],
                    ]
                );
            }

            // SalesoutAttached::where('salesout_id',$id)->delete();
            // $Salesout->detailscheckAll()->createMany($data['FEntry']);  
            DB::commit();
            return ['code'=>1000,'message'=>'修改成功'];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }

    }



    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
       
        try {
            //开始起事务
            DB::beginTransaction();
            Salesreturn::where('id',$id)->delete();
            SalesreturnAttached::where('salesreturn_id',$id)
            ->delete();
            DB::commit();
            return '删除成功';
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException('服务器飞出地球了请联系技术找回');
        }
    }

    //审核金蝶推送
    public static function pdassanningaddData($id)
    {
            //汇总数据
            $Salesreturn = Salesreturn::query()->select('returnnumber','id')->find($id);
            // ->with(['detailscheckAll'])
            $SalesreturnAttached = SalesreturnAttached::select( 'salesreturn_id','salesout_id',DB::raw('SUM(quantity) as quantity'),'storagelocation','salesout_attached_id')
            ->where('salesreturn_id',$Salesreturn['id'])
            ->groupby(['salesout_id','storagelocation','salesout_attached_id','salesreturn_id'])
            ->get()
            ->toArray();

            if(empty($Salesreturn)||empty($SalesreturnAttached)){
              return  throw new FailedException('销售退货单数据查询出错');
            }
            $datares = SalesreturnAttached::select( 'salesreturn_id','salesout_id','quantity','storagelocation','barcode','salesout_attached_id')
            ->where('salesreturn_id',$Salesreturn['id'])
            // ->groupby(['salesout_id','storagelocation','salesout_attached_id'])
            ->get()
            ->toArray();

            //数据汇总录入
            foreach($SalesreturnAttached as $k=>$v){
                    $Model[$k]['FGIVEAWAY'] = 'false';
                    $Model[$k]['FGIVEAWAYQTY'] = 0;//赠品数量
                    $SalesoutAttached = SalesoutAttached::select(
                        'salesout_attached.salesout_id',
                        'salesout_attached.fmaterialid',
                        'salesout_attached.fentryid',
                        'salesout_attached.fmaterialname',
                        'salesout_attached.fmaterialmodel',
                        'salesout_attached.fmodel',
                        'salesout_attached.funitid_number',
                        'salesout_attached.funitid_name',
                        'salesout_attached.fseq',
                        'salesout_attached.fqty',
                        'salesout.fid',
                        'salesout.fbillno',
                        // 'salesout.fid',
                        'salesout.fsaleorgid_number',
                        'salesout.fsupplierid_number',
                        'salesout_attached.fownertypeid',
                        'salesout_attached.fownerid_number',
                        'salesout_attached.fownerid_name',
                        )
                    ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
                    ->where('salesout_attached.id',$v['salesout_attached_id'])
                    ->where('salesout_attached.salesout_id',$v['salesout_id'])
                    ->first();
                   

                    $Storagelocation = Storagelocation::select(
                        'stash.fnumber',
                        'stash.fname',
                        'stash.fuseorgid_number',
                        'stash.fuseorgid_name',
                        'owning_id',
                        'storagelocation.warehousecode',
                        'storagelocation.repositoryname',
                        'storagelocation.id'
                    )
                    ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                    ->where('storagelocation.id',$v['storagelocation'])
                    ->first();
                    if(empty($Storagelocation)){
                        return throw new FailedException('库位出错');
                    }
        
                    $Model[$k]['FORGID'] = $SalesoutAttached['fsaleorgid_number'];//组织编码
                    $Model[$k]['FSRCBILLNO'] = $SalesoutAttached['fbillno'];//销售出原单号
                    $Model[$k]['FSRCSEQ'] = $SalesoutAttached['fseq'];
                    $Model[$k]['FMATERIALID'] = $SalesoutAttached['fmaterialid'];    
                    $Model[$k]['FUNITID'] = $SalesoutAttached['funitid_number'];
                    $Model[$k]['FQTY'] = $v['quantity'];
                    $Model[$k]['FSRCID'] = $SalesoutAttached['fid'];//行号id
                    $Model[$k]['FSRCENTRYID'] = $SalesoutAttached['fentryid'];//单据合并
                    $Model[$k]['FSTOCKID']= $Storagelocation['fnumber'];//仓库名称
                    $Model[$k]['FOwnerTypeId'] = $SalesoutAttached['fownertypeid'];//货主类型
                    $Model[$k]['FOwnerId'] = $SalesoutAttached['fownerid_number'];//货主编码

                    $Model[$k]['FSTOCKID'] = $Storagelocation['fnumber'];

                    // $fbillno = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$v['storagelocation'])->first();
                    // if(empty($fbillno)){
                    //      return throw new FailedException('库位出错');
                    // }
                    // if(isset($resdata[$fbillno->owning_id])){
                    //     $Model[$k]['FSTOCKID']= $resdata[$fbillno->owning_id]['FNumber'];
                    // }else{
                    //    return throw new FailedException('库位出错');
                    // }
                }

                try {
                    //开始起事务
                    DB::beginTransaction();
                    //数据明细
                   foreach($datares as $k=>$v){
                        $SalesoutAttached = SalesoutAttached::select(
                            'salesout_attached.salesout_id',
                            'salesout_attached.fmaterialid',
                            'salesout_attached.fentryid',
                            'salesout_attached.fmaterialname',
                            'salesout_attached.fmaterialmodel',
                            'salesout_attached.fmodel',
                            'salesout_attached.funitid_number',
                            'salesout_attached.funitid_name',
                            'salesout_attached.fseq',
                            'salesout_attached.fqty',
                            'salesout.fid',
                            'salesout.fbillno',
                            // 'salesout.fid',
                            'salesout.fsaleorgid_number',
                            'salesout.fsupplierid_number',
                            'salesout_attached.fownertypeid',
                            'salesout_attached.fownerid_number',
                            'salesout_attached.fownerid_name',
                            )
                        ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
                        ->where('salesout_attached.id',$v['salesout_attached_id'])
                        ->where('salesout_attached.salesout_id',$v['salesout_id'])
                        ->first();

                        $storagelocation = DB::table('storagelocation')->select('owning_id','warehousecode','repositoryname')->where('id',$v['storagelocation'])->first();
                        if(empty($storagelocation)){
                            return throw new FailedException('库位出错');
                        }
                        $inventory = [
                            'org_code'=>$SalesoutAttached['fsaleorgid_number'],
                            'cargo_code'=>$SalesoutAttached['fownerid_number'],
                            'supplier_code'=>$SalesoutAttached['fsupplierid_number'],
                            'doc_id'=>$id,
                            'docno'=>$Salesreturn['returnnumber'], 
                            'doc_type'=>InvTransDocType::SALES_DELIVERY_RECEIPT->value,
                            'material_no'=>$SalesoutAttached['fmaterialid'],
                            'location'=>$storagelocation->warehousecode,
                            'qty'=>$v['quantity'],
                            'unit'=>$SalesoutAttached['funitid_number'],
                            'lotnum'=>$v['barcode'],
                        ];
                    $data = InventoryService::addInv($inventory);
                    
                    
                   }                   
                   Salesreturn::where('id',$Salesreturn['id'])
                   ->update([
                       'state'=>1,
                       'writestate'=>1,
                       'updated_at'=>time()
                   ]);
                    //金蝶推送
                    $FEntity = [];
                    foreach($Model as $k=>$v){
                        $FEntity[$v['FORGID']][$k]['FSRCSEQ'] = $v['FSRCSEQ'];
                        $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                        $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                        $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'] - $v['FGIVEAWAYQTY'];
                        $FEntity[$v['FORGID']][$k]['FSTOCKID'] = $v['FSTOCKID'];
                        $FEntity[$v['FORGID']][$k]['FGIVEAWAY'] = $v['FGIVEAWAY'];
                        $FEntity[$v['FORGID']][$k]['FSRCBILLNO'] = $v['FSRCBILLNO'];
                        $FEntity[$v['FORGID']][$k]['FSRCID'] = $v['FSRCID'];
                        $FEntity[$v['FORGID']][$k]['FSRCENTRYID'] = $v['FSRCENTRYID'];
                        $FEntity[$v['FORGID']][$k]['FGIVEAWAYQTY'] = $v['FGIVEAWAYQTY'];
                    }
                    
                    foreach($FEntity as $k=>$v){
                                $order = [
                                    'FID'=>0,
                                    'FORGID'=>$k,//组织（传编码）
                                    'FBillNo'=>$Salesreturn['returnnumber'],
                                    'FDATE'=>date('Y-m-d H:i:s',time()),
                                    'FBILLTYPEID'=>"SAL_RETURNSTOCK",
                                    //'FSRCBILLNO'=>$k,
                                    'FEntity'=>$v,
                                ];
                            //金蝶推送
                            (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
                    }
                    DB::commit();
                    return ['code'=>1000,'message'=>'提交成功'];
                } catch (\Exception $e) {
                    DB::rollBack();
                    throw $e;
            }
    }
    
    //wms 数量修改
    public static function Modify($id,$data)
    {
        try {
            //开始起事务
            DB::beginTransaction();
            SalesoutTiaoma::where('id',$id)->update($data);
            DB::commit();
            return;
        } catch (\Exception $e) {
            DB::rollBack();
            throw new FailedException($e);
        }

    }

     //wms 详情接口
     public static function DetailinterfaceData($id,$data)
     {
 
         $Salesreturn = Salesreturn::select('returnnumber','remark','state','writestate')->where('id',$id)->first();
         
         $Salesreturn['writestate'] =  $Salesreturn->writestate == 1?'回写成功':'';
         $Salesreturn['description'] =  $Salesreturn->state == 1?'已审核':'待审核';
      
 
 
         $data['Salesreturn'] = $Salesreturn;
         $datares = SalesreturnAttached::query();
      
         if(!isset($data['all'])){ 
          
            $datares->select('salesreturn_id','salesout_id','salesout_attached_id','quantity','barcode','storagelocation')
           ->where('salesreturn_id',$id)
            ->get()
            ->toArray();
         }else{
             //汇总
             $datares->select(DB::raw('SUM(quantity) as quantity'),'salesout_id','storagelocation','salesout_attached_id')
             ->where('salesreturn_id',$id)
             ->groupby(['salesout_id','storagelocation','salesout_attached_id']);
         }
 
         $datares = $datares->get()->toArray();
      foreach($datares as $k=>$v){
  
             $salesout_id = SalesoutAttached::
             select(
                 'salesout.fbillno',
                 'salesout.fsaleorgid_number',
                 'salesout.fsaleorgid_name',
                 'salesout.fcustomerid_number',
                 'salesout.fcustomerid_name',
                 'salesout_attached.fmaterialid',
                 'salesout_attached.fmaterialname',
                 'salesout_attached.fmaterialmodel',
                 'salesout_attached.fmodel',
                 'salesout_attached.funitid_number',
                 'salesout_attached.funitid_name',
                 'salesout_tiaoma.barcode',
                 // 'salesout_attached.fstockid_number',
                 // 'salesout_attached.fstockid_name',
                 )
             ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
             ->join('salesout_tiaoma as salesout_tiaoma', 'salesout_tiaoma.salesout_attached_id', '=', 'salesout_attached.id')
             ->where('salesout.id',$v['salesout_id'])
             ->where('salesout_attached.id',$v['salesout_attached_id'])
             ->where('salesout_tiaoma.salesout_id',$v['salesout_id'])
             ->where('salesout_tiaoma.salesout_attached_id',$v['salesout_attached_id'])
             ->first();
 
             $datares[$k]['fbillno'] = $salesout_id->fbillno;
             $datares[$k]['fsaleorgid_number'] = $salesout_id->fsaleorgid_number;
             $datares[$k]['fsaleorgid_name'] = $salesout_id->fsaleorgid_name;
             $datares[$k]['fcustomerid_number'] = $salesout_id->fcustomerid_number;
             $datares[$k]['fcustomerid_name'] = $salesout_id->fcustomerid_name;
             $datares[$k]['fmaterialid'] = $salesout_id->fmaterialid;
             $datares[$k]['fmaterialname'] = $salesout_id->fmaterialname;
             $datares[$k]['fmaterialmodel'] = $salesout_id->fmaterialmodel;
             $datares[$k]['fmodel'] = $salesout_id->fmodel;
             $datares[$k]['funitid_number'] = $salesout_id->funitid_number;
             $datares[$k]['funitid_name'] = $salesout_id->funitid_name;
             $datares[$k]['barcode'] = $salesout_id->barcode;
            
             $fbillno = DB::table('storagelocation')
             ->select('storagelocation.warehousecode','storagelocation.repositoryname','stash.fnumber','stash.fname')
             ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
             ->where('storagelocation.id',$v['storagelocation'])->first();
             if(!empty($fbillno)){
                 
                $datares[$k]['warehousecode'] = $fbillno->warehousecode;
                $datares[$k]['repositoryname'] = $fbillno->repositoryname;
                $datares[$k]['fnumber'] = $fbillno->fnumber;
                $datares[$k]['fname'] = $fbillno->fname;
             }else{
                $datares[$k]['warehousecode'] = '';
                $datares[$k]['repositoryname'] = '';
                $datares[$k]['fnumber'] = '';
                $datares[$k]['fname'] = '';
             }
 
           
 
         }
 
         $data['detailscheck_all'] = $datares;
          return ['code'=>1000,'message'=>'请求成功','data'=>$data];
 
     }
 
  
   //PDA箱号扫描接口
   public static function codedata($code)
    {
        $SalesoutTiaoma = SalesoutTiaoma::select(
            'salesout_tiaoma.id',
            'salesout_tiaoma.salesout_id',
            'salesout_tiaoma.salesout_attached_id',
            'salesout_tiaoma.barcode',
            'salesout.fbillno',
            'salesout.incomingtype',
            'salesout.fsaleorgid_name',
            // 'salesout.fcustomerid_number',
            'salesout.fcustomerid_name',
            'salesout_attached.fmaterialid',
            'salesout_attached.fmaterialname',
            'salesout_attached.fmaterialmodel',
            'salesout_attached.fmodel',
            'salesout_attached.funitid_number',
            'salesout_attached.funitid_name',
            'salesout_attached.fqty',
            )
        ->join('salesout as salesout', 'salesout.id', '=', 'salesout_tiaoma.salesout_id')
        ->join('salesout_attached as salesout_attached', 'salesout_attached.id', '=', 'salesout_tiaoma.salesout_attached_id')
        ->where('salesout_tiaoma.barcode',$code)
        ->first();
        if(empty($SalesoutTiaoma)){
            return throw new FailedException('亲，销售出库单没有这箱号无法退货。');
           }
        
        if(!empty($SalesoutTiaoma)){
            $kc = DB::table('inventory')
            ->where('lot_num',$SalesoutTiaoma->barcode)
            ->where('material_no',$SalesoutTiaoma->fmaterialid)//SKU
            ->first();
            $SalesoutTiaoma['inventoryqty'] = $kc->qty - $kc->assign_qty - $kc->lock_qty;
            $fbillno = DB::table('storagelocation')
            ->select('storagelocation.warehousecode','storagelocation.repositoryname','stash.fnumber','stash.fname')
            ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
            ->where('warehousecode',$kc->location)->first();
            $SalesoutTiaoma['warehousecode'] = $fbillno->warehousecode;
            $SalesoutTiaoma['repositoryname'] = $fbillno->repositoryname;
            $SalesoutTiaoma['fnumber'] = $fbillno->fnumber;
            $SalesoutTiaoma['fname'] = $fbillno->fname;
        }
        return ['code'=>1000,'message'=>'请求成功','data'=>$SalesoutTiaoma];
    

    }

    //组织间 PDA箱号扫描接口 + 金蝶推送
   public static function codetissueData($code)
   {
                $kc = DB::table('inventory')
                ->where('lot_num',$code)
                // ->where('material_no',$$code)//SKU
                ->first();
                if($kc->qty == 0){
                    return throw new FailedException('亲，没有库存数量无法退货。');
                }
                

            $SalesoutTiaoma = SalesoutTiaoma::select(
                'salesout_tiaoma.id',
                'salesout_tiaoma.salesout_id',
                'salesout_tiaoma.salesout_attached_id',
                'salesout_tiaoma.barcode',
                'salesout.fbillno',
                'salesout.incomingtype',
                'salesout.fsaleorgid_name',
                // 'salesout.fcustomerid_number',
                'salesout.fcustomerid_name',
                'salesout_attached.fmaterialid',
                'salesout_attached.fmaterialname',
                'salesout_attached.fmaterialmodel',
                'salesout_attached.fmodel',
                'salesout_attached.funitid_number',
                'salesout_attached.funitid_name',
                'salesout_attached.fqty',
                )
            ->join('salesout as salesout', 'salesout.id', '=', 'salesout_tiaoma.salesout_id')
            ->join('salesout_attached as salesout_attached', 'salesout_attached.id', '=', 'salesout_tiaoma.salesout_attached_id')
            ->where('salesout_tiaoma.barcode',$code)
            ->first();

            if(empty($SalesoutTiaoma)){
                return throw new FailedException('亲，销售出库单没有这箱号无法退货。');
            }

            $PurchasereturnAttached = PurchasereturnAttached::select(
                'purchasereturn_attached.barcode',
                'purchasereturn_attached.storagelocation',
                'purchasereturn_attached.purchasewarehousing_id',
                'purchasereturn_attached.purchasewarehousing_materiel_id',
                'purchasereturn.returnnumber',
                'purchasereturn.fbillno',
                'purchasereturn.incomingtype',
                'purchasereturn_attached.quantityreturned',
            )
            ->join('purchasereturn as purchasereturn', 'purchasereturn.id', '=', 'purchasereturn_attached.purchasereturn_id')
            ->where('purchasereturn_attached.barcode',$code)
            ->where('purchasereturn.incomingtype',1)
            ->first();

            if(empty($PurchasereturnAttached)){
                return throw new FailedException('亲，组织间退货单没有这箱号无法退货。');
            }

            $PurchasewarehousingMateriel = PurchasewarehousingMateriel::select(
                'purchasewarehousing.fbillno',
                'purchasewarehousing.incomingtype',
                'purchasewarehousing_materiel.fmaterialid',
                'purchasewarehousing_materiel.fmaterialname',
                'purchasewarehousing_materiel.fmaterialmodel',
                'purchasewarehousing_materiel.fmodel',
                'purchasewarehousing_materiel.funitid_number',
                'purchasewarehousing_materiel.funitid_name',
                'purchasewarehousing_materiel.fentryid',
                )
            ->join('purchasewarehousing as purchasewarehousing', 'purchasewarehousing.id', '=', 'purchasewarehousing_materiel.purchasewarehousing_id')
            ->where('purchasewarehousing_materiel.id',$PurchasereturnAttached['purchasewarehousing_materiel_id'])
            //   ->where('purchasewarehousing_materiel.barcode',$code)
            ->where('purchasewarehousing.incomingtype',1)
            ->first();

            if(empty($PurchasewarehousingMateriel)){
                return throw new FailedException('亲，组织间没有该条入库箱号。');
            }

            //查出销售退货的数据-》根据销售单号 SalesoutAttached Salesout
            $salesout =  SalesoutAttached::select('salesout.id as salesout_id','salesout_attached.id as salesout_attached_id','salesout.fbillno','salesout_attached.fqty')
            ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
            ->where('salesout.fbillno',$PurchasewarehousingMateriel['fbillno'])
            ->where('salesout.incomingtype',1)
            ->where('salesout_attached.fmaterialid',$PurchasewarehousingMateriel['fmaterialid'])
            ->where('salesout_attached.fentryid',$PurchasewarehousingMateriel['fentryid'])
            ->first();

            if(empty($salesout)){
                return throw new FailedException('亲，组织间没有该条销售出库数据。');
            }

            $SalesreturnAttached =  SalesreturnAttached::select('salesreturn.id','salesreturn.returnnumber','salesreturn_attached.salesout_id','salesreturn_attached.salesout_attached_id','salesreturn_attached.salesreturn_id')
            ->join('salesreturn as salesreturn', 'salesreturn.id', '=', 'salesreturn_attached.salesreturn_id')
            ->where('salesreturn_attached.salesout_id',$salesout['salesout_id'])
            ->where('salesreturn.incomingtype',1)
            ->where('salesreturn.fbillno',$salesout['fbillno'])
            ->where('salesreturn_attached.salesout_id',$salesout['salesout_id'])
            ->where('salesreturn_attached.salesout_attached_id',$salesout['salesout_attached_id'])
            ->first();

                
            if(empty($SalesreturnAttached)){
                return throw new FailedException('亲，组织间没有该条采购退货单数据。');
            }
                
                $countdata = SalesreturnAttached::select('id')->where('id',$SalesreturnAttached['id'])->count();//该条退货单总的销售退货数据

                $PurchasewarehousingMateriel['inventoryqty'] = $kc->qty - $kc->assign_qty - $kc->lock_qty;
                
                $fbillno = DB::table('storagelocation')
                ->select('storagelocation.warehousecode','storagelocation.repositoryname','stash.fnumber','stash.fname')
                ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                ->where('warehousecode',$kc->location)->first();
                
                $PurchasewarehousingMateriel['warehousecode'] = $fbillno->warehousecode;
                $PurchasewarehousingMateriel['repositoryname'] = $fbillno->repositoryname;
                $PurchasewarehousingMateriel['fnumber'] = $fbillno->fnumber;
                $PurchasewarehousingMateriel['fname'] = $fbillno->fname;
                $PurchasewarehousingMateriel['fname'] = $fbillno->fname;
                $PurchasewarehousingMateriel['quantityreturned'] = $PurchasereturnAttached['quantityreturned'];
                $PurchasewarehousingMateriel['fbillno'] = $PurchasewarehousingMateriel['fbillno'];
                $PurchasewarehousingMateriel['incomingtype'] = $SalesreturnAttached['incomingtype'];
                $PurchasewarehousingMateriel['salesout_id'] = $SalesreturnAttached['salesout_id'];
                $PurchasewarehousingMateriel['salesout_attached_id'] = $SalesreturnAttached['salesout_attached_id'];
                $PurchasewarehousingMateriel['salesreturn_id'] = $SalesreturnAttached['salesreturn_id'];
                $PurchasewarehousingMateriel['returnnumber'] = $SalesreturnAttached['returnnumber'];
                $PurchasewarehousingMateriel['countdata'] = $countdata;
                $PurchasewarehousingMateriel['fqty'] = $salesout['fqty'];
                
            return ['code'=>1000,'message'=>'请求成功','data'=>$PurchasewarehousingMateriel];
   
   }

     //组织间  金蝶推送
     public static function submitdataAdd($data)
     {

                //汇总数据
                $Salesreturn = Salesreturn::query()->select('returnnumber','id')->where('returnnumber',$data['returnnumber'])->where('fbillno',$data['fbillno'])->where('incomingtype',$data['incomingtype'])->first();
                    
                if(empty($Salesreturn['returnnumber'])){
                    throw new FailedException('没有该条退货单数据');
                }
                
                try {
                    //开始起事务
                    DB::beginTransaction();
                    //数据明细
                    foreach($data['detailscheck_all'] as $k=>$v){
                        $Model[$k]['FGIVEAWAY'] = 'false';
                        $Model[$k]['FGIVEAWAYQTY'] = 0;//赠品数量
                        $SalesoutAttached = SalesoutAttached::select(
                            'salesout_attached.salesout_id',
                            'salesout_attached.fmaterialid',
                            'salesout_attached.fentryid',
                            'salesout_attached.fmaterialname',
                            'salesout_attached.fmaterialmodel',
                            'salesout_attached.fmodel',
                            'salesout_attached.funitid_number',
                            'salesout_attached.funitid_name',
                            'salesout_attached.fseq',
                            'salesout_attached.fqty',
                            'salesout.fid',
                            'salesout.fbillno',
                            // 'salesout.fid',
                            'salesout.fsaleorgid_number',
                            'salesout.fsupplierid_number',
                            'salesout_attached.fownertypeid',
                            'salesout_attached.fownerid_number',
                            'salesout_attached.fownerid_name',
                            )
                        ->join('salesout as salesout', 'salesout.id', '=', 'salesout_attached.salesout_id')
                        ->where('salesout_attached.id',$v['salesout_attached_id'])
                        ->where('salesout_attached.salesout_id',$v['salesout_id'])
                        ->first();

                        if(empty($SalesoutAttached)){
                            return throw new FailedException('亲！无法找到该销售单号信息');
                        }

                        
                        $Storagelocation = Storagelocation::select(
                            'stash.fnumber',
                            'stash.fname',
                            'stash.fuseorgid_number',
                            'stash.fuseorgid_name',
                            'owning_id',
                            'storagelocation.warehousecode',
                            'storagelocation.repositoryname',
                            'storagelocation.id'
                        )
                        ->join('stash as stash', 'stash.id', '=', 'storagelocation.owning_id')
                        ->where('storagelocation.id',$v['storagelocation'])
                        ->first();
                        if(empty($Storagelocation)){
                            return throw new FailedException('库位出错');
                        }
                        
            
                        $Model[$k]['FORGID'] = $SalesoutAttached['fsaleorgid_number'];//组织编码
                        $Model[$k]['FSRCBILLNO'] = $SalesoutAttached['fbillno'];//销售出原单号
                        $Model[$k]['FSRCSEQ'] = $SalesoutAttached['fseq'];
                        $Model[$k]['FMATERIALID'] = $SalesoutAttached['fmaterialid'];    
                        $Model[$k]['FUNITID'] = $SalesoutAttached['funitid_number'];
                        $Model[$k]['FQTY'] = $v['quantity'];
                        $Model[$k]['FSRCID'] = $SalesoutAttached['fid'];//行号id
                        $Model[$k]['FSRCENTRYID'] = $SalesoutAttached['fentryid'];//单据合并
                        $Model[$k]['FSTOCKID']= $Storagelocation['fnumber'];//仓库名称
                        $Model[$k]['FOwnerTypeId'] = $SalesoutAttached['fownertypeid'];//货主类型
                        $Model[$k]['FOwnerId'] = $SalesoutAttached['fownerid_number'];//货主编码

                        
                        //加库存
                        $inventory = [
                            'org_code'=>$SalesoutAttached['fsaleorgid_number'],
                            'cargo_code'=>$SalesoutAttached['fownerid_number'],
                            'supplier_code'=>$SalesoutAttached['fsupplierid_number'],
                            'doc_id'=>$Salesreturn['id'],
                            'docno'=>$Salesreturn['returnnumber'], 
                            'doc_type'=>InvTransDocType::SALES_DELIVERY_RECEIPT_TISSUE->value,
                            'material_no'=>$SalesoutAttached['fmaterialid'],
                            'location'=>$Storagelocation['warehousecode'],
                            'qty'=>$v['quantity'],
                            'unit'=>$SalesoutAttached['funitid_number'],
                            'lotnum'=>$v['barcode'],
                        ];

                        $data = InventoryService::addInv($inventory);
                    }                   
                        Salesreturn::where('id',$Salesreturn['id'])
                        ->update([
                            'state'=>1,
                            'writestate'=>1,
                            'updated_at'=>time()
                        ]);
                    //金蝶推送
                    $FEntity = [];
                    foreach($Model as $k=>$v){
                        $FEntity[$v['FORGID']][$k]['FSRCSEQ'] = $v['FSRCSEQ'];
                        $FEntity[$v['FORGID']][$k]['FMATERIALID'] = $v['FMATERIALID'];
                        $FEntity[$v['FORGID']][$k]['FUNITID'] = $v['FUNITID'];
                        $FEntity[$v['FORGID']][$k]['FQTY'] = $v['FQTY'] - $v['FGIVEAWAYQTY'];
                        $FEntity[$v['FORGID']][$k]['FSTOCKID'] = $v['FSTOCKID'];
                        $FEntity[$v['FORGID']][$k]['FGIVEAWAY'] = $v['FGIVEAWAY'];
                        $FEntity[$v['FORGID']][$k]['FSRCBILLNO'] = $v['FSRCBILLNO'];
                        $FEntity[$v['FORGID']][$k]['FSRCID'] = $v['FSRCID'];
                        $FEntity[$v['FORGID']][$k]['FSRCENTRYID'] = $v['FSRCENTRYID'];
                        $FEntity[$v['FORGID']][$k]['FGIVEAWAYQTY'] = $v['FGIVEAWAYQTY'];
                    }
                    
                    foreach($FEntity as $k=>$v){
                                $order = [
                                    'FID'=>0,
                                    'FORGID'=>$k,//组织（传编码）
                                    'FBillNo'=>$Salesreturn['returnnumber'],
                                    'FDATE'=>date('Y-m-d H:i:s',time()),
                                    'FBILLTYPEID'=>"SAL_RETURNSTOCK",
                                    //'FSRCBILLNO'=>$k,
                                    'FEntity'=>$v,
                                ];
                            //金蝶推送
                            (new KingDeeService())->form('TVJB_DJWMSDJ')->invokeSave($order);
                    }
                    DB::commit();
                    return ['code'=>1000,'message'=>'提交成功'];
                } catch (\Exception $e) {
                    DB::rollBack();
                        throw $e;
                }



     
  
     }
     


      
}
